package com.beiding.fastmock.utils;

import eu.medsea.mimeutil.MimeUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class HttpUtils {

    static {
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
    }

    public static void loadFile(File file, HttpServletRequest request, HttpServletResponse response, Map<String, Object> config) {

        //是否作为下载项目
        Boolean download = (Boolean) config.getOrDefault("download", false);
        String fileName = (String) config.get("fileName");

        BufferedInputStream bis = null;
        try {
            if (file.exists()) {
                long p = 0L;
                long toLength;
                long contentLength;
                long fileLength;
                String rangBytes = "";
                fileLength = file.length();
                boolean isPart=false;//是否读取一段内容,而非全部
                // get file content
                InputStream ins = new FileInputStream(file);
                bis = new BufferedInputStream(ins);

                // tell the client to allow accept-ranges
                response.reset();
                //支持断点续传
                response.setHeader("Accept-Ranges", "bytes");


                // client requests a file block download start byte
                String range = request.getHeader("Range");
                if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
//                    200是OK（一切正常），206是Partial Content（服务器已经成功处理了部分内容），
//                    416 Requested Range Not Satisfiable（对方（客户端）发来的Range 请求头不合理）。
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                    rangBytes = range.substring("bytes=".length());
                    if (rangBytes.endsWith("-")) { // bytes=270000-
                        p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                        contentLength = fileLength - p; // 客户端请求的是270000之后的字节（包括bytes下标索引为270000的字节）
                    } else if (rangBytes.startsWith("-")) {//bytes=-500
                        //读取最后一定数量的内容
                        contentLength = Long.parseLong(rangBytes.substring(1));
                        p = fileLength - contentLength + 1;

                    } else { // bytes=270000-320000
                        isPart = true;
                        String temp1 = rangBytes.substring(0, rangBytes.indexOf("-"));
                        String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1);
                        p = Long.parseLong(temp1);
                        toLength = Long.parseLong(temp2);
                        contentLength = toLength - p + 1; // 客户端请求的是 270000-320000 之间的字节
                    }
                } else {
                    contentLength = fileLength;
                }

                // 如果设设置了Content-Length，则客户端会自动进行多线程下载。如果不希望支持多线程，则不要设置这个参数。
                // Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节]
                response.setHeader("Content-Length", contentLength + "");

                // 断点开始
                // 响应的格式是:
                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]

                String contentRange = "bytes " + p + "-" + (fileLength - 1) + "/" + fileLength;
                response.setHeader("Content-Range", contentRange);

                if (p > 0) {
                    bis.skip(p);
                }

                if (download) {
                    if (fileName == null) {
                        fileName = file.getName();
                    }
                    response.setContentType("application/octet-stream");
                    response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                } else {

                    Collection<?> mimeTypes = MimeUtil.getMimeTypes(file);
                    Iterator<?> iterator = mimeTypes.iterator();
                    StringBuilder builder = new StringBuilder();
                    if (iterator.hasNext()) {
                        builder.append(iterator.next());
                        while (iterator.hasNext()) {
                            builder.append(";").append(iterator.next());
                        }
                    }
                    response.setContentType(builder.toString());
                }

                OutputStream out = response.getOutputStream();
                int n = 0;
                long readLength = 0;
                int bsize = 1024;
                byte[] bytes = new byte[bsize];
                if (isPart) {
                    // 针对 bytes=27000-39000 的请求，从27000开始写数据
                    while (readLength <= contentLength - bsize) {
                        n = bis.read(bytes);
                        readLength += n;
                        out.write(bytes, 0, n);
                    }
                    if (readLength <= contentLength) {
                        n = bis.read(bytes, 0, (int) (contentLength - readLength));
                        out.write(bytes, 0, n);
                    }
                } else {
                    while ((n = bis.read(bytes)) != -1) {
                        out.write(bytes, 0, n);
                    }
                }
                out.flush();

            }
        } catch (IOException ie) {
            // 忽略 ClientAbortException 之类的异常
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
